package com.tian.intercptor;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.validation.beanvalidation.SpringValidatorAdapter;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

/**
 * @author tianwc  公众号：java后端技术全栈、面试专栏
 * @version 1.0.0
 * @date 2023年5月27日 20:40
 */
@Slf4j
@Aspect
@Component
@Order(9)
public class ParameterCheckInspect {

    @Autowired
    private SpringValidatorAdapter springValidatorAdapter;

    @Before(value = "execution(public * com.tian.controller.*.*(..))")
    public void before(JoinPoint joinPoint) {
        for (Object arg : joinPoint.getArgs()) {
            Set<ConstraintViolation<Object>> violationSet = springValidatorAdapter.validate(arg);
            if (!violationSet.isEmpty()) {
                throw new ConstraintViolationException(violationSet.iterator().next().getMessage(), null);
            }
            return;
        }
    }
}

